<?php

namespace Api\Controller;

use Think\Controller;
use Common\Logic\ImLogic;
use Common\Logic\TelBookLogic;

class ImController extends BaseController 
{

	protected $logic;

	public function  __construct()
    {
        parent::__construct();

        $this->logic = new ImLogic;

        // $this->user_id = I('user_id');

        // if ( !$this->user_id ) 
        // {
        // 	$this->returnInfo(0,"未登录");
        // }
    }

    // public function test()
    // {
    // 	$tels = [];
    // 	for($i = 0;$i<1000;$i++)
    // 	{
    // 		$tels[] = 18812345670 + $i;
    // 	}
    // 	var_dump(json_encode($tels));
    // }


    /** 
    * 加好友
    * @param user_id
    * @param friend_id
    */ 
	public function addFriend()
	{ 
		$friend_id = I('friend_id');

		$res = $this->logic->addFriend($this->user_id,$friend_id);

		echo json_encode($res,JSON_UNESCAPED_UNICODE);
	}

	/** 
    * 删除好友
    * @param user_id
    * @param friend_id
    */ 
	public function delFriend()
	{ 
		$friend_id = I('friend_id');

		$res = $this->logic->delFriend($this->user_id,$friend_id);

		echo json_encode($res,JSON_UNESCAPED_UNICODE);
		
	}


	/** 
    * 同意加好友
    * @param $id (好友表id，如果不传，下面的参数必须传)
    * @param $user_id 
    * @param $firnd_id 
    */ 
	public function confirmFirend()
	{ 
		$params = I();

		$params['user_id'] = $this->user_id;

		$res = $this->logic->confirmFirend($params);

		echo json_encode($res,JSON_UNESCAPED_UNICODE);

	}

	/** 
    * 拒绝加好友
    * @param $id (好友表id，如果不传，下面的参数必须传)
    * @param $user_id 
    * @param $firnd_id 
    */ 
	public function refuseFirend()
	{ 
		$params = I();

		$params['user_id'] = $this->user_id;

		$res = $this->logic->refuseFirend($this->user_id,$friend_id);

		echo json_encode($res,JSON_UNESCAPED_UNICODE);
	}

	

	/** 
    * 获取好友列表
    * @param user_id
    */ 
	public function getFriendList()
	{ 
		// $res = $this->logic->getFriendList($this->user_id);
		$isUpdate = I("for_update",0);
		$page =  I("page",0) ? I("page",0) : ( I("p",0) ? I("p",0) : 0 );
		$res = $this->logic->getFriendListRemote($this->user_id,$page, $isUpdate > 0 );

		$res['recomand'] = [];

		if($res['count']==0)
		{
			$recomand = TelBookLogic::getRecomand($this->user_id);

			if( $recomand && !empty($recomand['result']) )
				$res['recomand'] = $recomand['result'];
		}

		$this->returnInfo(1,'ok',$res);
	}

    
    /** 
    * 创建群
    * @param user_id
    * @param name
    * @param avatar
    * @param desc 可空
    * @param firend_ids 数组json字符串 可空 
    */ 
	public function createGroup()
	{
		$params = I();

		#看看是否上传头像了
		if($_FILES)
		{
			$upload = new \Think\Upload();// 实例化上传类
			$upload->maxSize   =    $map['author'] = (1024*1024*3);// 设置附件上传大小 管理员10M  否则 3M
			$upload->exts      =     array('jpg', 'gif', 'png');// 设置附件上传类型
			$upload->rootPath  =     './Public/upload/group_avatar/'; // 设置附件上传根目录
			$upload->replace  =     true; // 存在同名文件是否是覆盖，默认为false
			//$upload->saveName  =   'file_'.$id; // 存在同名文件是否是覆盖，默认为false
			// 上传文件 
			$info   =   $upload->upload();  
			if(!$info) {// 上传错误提示错误信息   
				$this->returnInfo(-1,$upload->getError());
			}else{
				foreach ($info as $key => $value) 
				{
					$params['avatar'] =  $value['urlpath'];
				} 
			}                     
		}

		#埋坑，填坑，自己的坑
		if( isset($params['firend_ids']) && !isset($params['friend_ids']) )
		{
			$params['friend_ids'] = $params['firend_ids'];
			unset($params['firend_ids']);
		}

		$params['user_id'] = $this->user_id;

		$res = $this->logic->createGroup($params);

		echo json_encode($res,JSON_UNESCAPED_UNICODE);

	}


	/** 
    * 获取群信息
    * @param groupid
    */ 
	public function getGroupInfo()
	{
		$groupid = I("groupid");

		$gorup = $this->logic->getGroupInfo($groupid);

		if($gorup)
		{
			$res = [
				"status" => 1,
				"msg" => "获取成功",
				"result" => $gorup
			];
		}else{
			$res = [
				"status" => -1,
				"msg" => "群不存在",
				"result" => ""
			];
		}

		if( $this->platform == 2 )
		{
			echo json_encode($res,JSON_UNESCAPED_UNICODE);
		}else{
			echo json_encode($gorup,JSON_UNESCAPED_UNICODE);
		}
	}


	/** 
    * 修改群信息
    * @param groupid/id
    * @param name 可空
    * @param avatar 可空
    * @param desc 可空
    */ 
	public function modifyGroup()
	{
		$params = I();

		$res = $this->logic->modifyGroup($params);

		echo json_encode($res,JSON_UNESCAPED_UNICODE);

	}


	/** 
    * 拉人进群，必须互相关注
    * @param user_id  拉人的用户id
	* @param groupid IM系统群id
	* @param friend_id 被拉入群的用户id  支持多人id array数组
    */ 
	public function joinGroup()
	{
		$params = I();

		$params['user_id'] = $this->user_id;

		$res = $this->logic->joinGroup($params);

		echo json_encode($res,JSON_UNESCAPED_UNICODE);
		
	}

	/** 
    * 获取群成员列表
    * @param id/groupid  id/im系统群id
    * @param page
    * @param page_size
    */ 
	public function getGroupMembers()
	{
		$params = I();

		$res = $this->logic->getGroupMembers($params);

		echo json_encode($res,JSON_UNESCAPED_UNICODE);
		
	}

	/** 
    * 退群
    * @param id/groupid  id/im系统群id
    * @param user_id
    */
    public function quitGroup( )
	{
		$params = I();

		$params['user_id'] = isset($params['user_id']) ? $params['user_id'] : $this->user_id;

		$res = $this->logic->quitGroup($params,  $this->user_id);

		echo json_encode($res,JSON_UNESCAPED_UNICODE);
		
	}

	/** 
    * 获取我添加的群列表
    * @param user_id
    */
    public function getGroupList()
	{ 
		$isUpdate = I("for_update",0);

		$res = $this->logic->getGroupsForUser($this->user_id,$isUpdate > 0);

		echo json_encode($res,JSON_UNESCAPED_UNICODE);
		
	}

	/** 
    * 保存用户的电话本，支持2000个电话，并返回电话本中注册的用户
    * @param mobile 数组json字符串
    * @param user_id
    */
    public function saveTelBook( )
	{
		$mobile = I('mobile');

		if( $mobile )
		{
			TelBookLogic::saveTelBook(json_decode($mobile,TRUE),$this->user_id);
		}

		$res = TelBookLogic::analyseTelBook($this->user_id);

		if( $res && $res['status'] == 1 )
		{
			$localData = $res['result'];

			$res['result'] = [];
			if( isset( $localData['friend'] ) )
			{
				foreach($localData['friend'] as $k )
				{
					if( $k == $this->user_id )
					{
						continue;
					}
					$info = TelBookLogic::getUserInfoById($k);
					$info['head_pic'] = parseMediaUrl($info['head_pic']);
					$info['is_reg'] = true;
					$info['is_self'] = false;
					$info['is_follow'] = true;
					$res['result'][] = $info;
				}
				unset($k);
			}
			if( isset( $localData['unfriend'] ) )
			{
				foreach($localData['unfriend'] as $k )
				{
					if( $k == $this->user_id )
					{
						continue;
					}
					$info = TelBookLogic::getUserInfoById($k);
					$info['head_pic'] = parseMediaUrl($info['head_pic']);
					$info['is_reg'] = true;
					$info['is_self'] = false;
					$info['is_follow'] = false;
					$res['result'][] = $info;
				}
				unset($k);
			}
		}

		echo json_encode($res,JSON_UNESCAPED_UNICODE);
		
	}

	/** 
    * 校验手机通讯录里的用户
    * @param mobile 数组json字符串
    * @param user_id
    */
    public function chkTelBook( )
	{
		$mobile = I('mobile');

		$res = TelBookLogic::chkTelBook(json_decode($mobile,TRUE),$this->user_id);
		$this->returnInfo(1,"ok",$res);
	}

	/** 
    * 获取用户信息
    * @param mobile 数组json字符串
    * @param user_id
    */
    public function userInfo( )
	{
		$user_id = I('user_id');
		$res = $this->logic->getUserInfoById($user_id);
		$this->returnInfo(1,"ok",$res);
	}

	/** 
    * 群主获取推荐的可以拉进群的用户信息
    * @param group_id
    * @param page
    */
    public function recoUsers( )
	{
		$group_id = I('group_id','');
		$page = I('page', 1);
//		 var_dump($this->user_id, $group_id, $page);
		$res = $this->logic->recoUsers($this->user_id, $group_id, $page);
		$this->returnInfo(1,"ok",$res);
	}

	/** 
    * 关键词查询用户
    * @param keyword
    * @param keyword
    * @param page
    */
    public function searchUser( )
	{
		$group_id = I('group_id',0);
		$keyword = I('keyword','');
		$page = I('page', 1);
		
		if( empty($keyword) )
		$this->returnInfo(0,"请输入关键词");

		
		$where['nickname'] = ['like','%'.$keyword.'%'];

		if( preg_match('/[\d]{4,11}/',$keyword ) )
		{ 
			$where['mobile'] = ['like','%'.$keyword.'%'];
			$where['_logic'] = 'or';
		}
		
		$model = M('users');

		$res['count'] = $model->where($where)->count();
		$res['list'] = $model->where($where)->field('user_id,nickname,mobile,head_pic')->page($page, 20)->select();

		if( $group_id > 0 )
		{
			$members = $this->logic->getGroupMembersArray([
				'groupid' => $group_id
			]);
		}

		foreach($res['list']  as $k => &$v)
		{
			$v['head_pic'] = \parseMediaUrl($v['head_pic']);
			$v['is_member'] = false;
			if( $group_id > 0 )
			{
				$v['is_member'] = in_array($v['user_id'], $members);
			}
		}

		$this->returnInfo(1,"ok",$res);
	}
}